#include<stdio.h>
#include<string.h>
#include"elfx.h"




int parse_args(int argc, char ** argv, int * mask_addr, char **path){
    int mask = 0;
    for(int i=0;i<argc;i++){
        char * s = argv[i];
        if( !strcmp(s,"-a") 
        || !strcmp(s,"a") ){
            mask = 0xffffffff;
        }else if( !strcmp(s,"-h")
        || !strcmp(s,"h") ){
            mask |= PRT_EHDR;
        }else if( !strcmp(s,"-S")
        || !strcmp(s,"S") ){
            mask |= PRT_SHDR;
        }else if( !strcmp(s,"-s")
        || !strcmp(s,"s") ){
            mask |= PRT_SYM;
        }else if( !strcmp(s,"-t")
        || !strcmp(s,"t") ){
            mask |= PRT_STR | PRT_SHSTR;
        }else if( !strcmp(s,"-r")
        || !strcmp(s,"r") ){
            mask |= PRT_REL;
        }else if( !strcmp(s,"-f")){
            if( i==argc-1 ||argv[i+1][0]=='-')return -1;
            *path = argv[i+1];
            i++;
        }else if( !strncmp(s,"-f",2) ){
            *path = s+2;
        }else{
            return -1; 
        }
    }
    *mask_addr = mask;
    return 0;
}
void print_help(){
    printf("Usage:\n");
    printf("  readelfx -f [-a -s -S -t -r  ]\n");
    printf("  readelfx --help\n");
    printf("    -f <file_path>:  the file_path is a elf file like xxx.o or xxx.so or xxx.a \n");
    printf("    -a:              print all information of the elf file identifier by file_path\n");
    printf("    -s:              print the symtab of elf file identifier by file_path\n");
    printf("    -t:              print the shstrtab and strtab of elf file identifier by file_path\n");
    printf("    -S:              print the all secitons of elf file identifier by file_path\n");
    printf("    -r:              print the all relocation table sections of elf file identifier by file_path\n");
}

int main(int argc, char ** argv){
    if(argc<2){
        print_help();        
        return -1;
    }
    
    char * path = NULL  ;
    int mask=0;

    if(parse_args(argc-1,argv+1,&mask,&path)){
        print_help();
        return -1;
    }
    if(!mask ){
        print_help();
        return -1;
    }
    if(  !path ){
        print_help();
        return -1;
    }
    
    if(!strlen(path) ){
        print_help();
        return -1;
    }

    elf64_t * elf = parse_elf64_file(path);
    
    print_elf64(elf,mask);
	return 0;
}
